/*
 * Copyright© 2003-2019 浙江汇信科技有限公司, All Rights Reserved.
 */
package com.icinfo.cloud.provider.punish.ucase.casemain.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.lang.Dict;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.icinfo.cloud.common.core.page.PageResponse;
import com.icinfo.cloud.common.security.util.UserUtil;
import com.icinfo.cloud.provider.common.constant.Constant;
import com.icinfo.cloud.provider.common.exception.BusinessException;
import com.icinfo.cloud.provider.common.utils.BaseUtil;
import com.icinfo.cloud.provider.punish.external.cadjjbxx.service.impl.ExternalService;
import com.icinfo.cloud.provider.punish.ucase.casemain.dto.*;
import com.icinfo.cloud.provider.punish.ucase.casemain.enums.CaseStatusEnum;
import com.icinfo.cloud.provider.punish.ucase.casemain.mapper.CaseHandlePersonRecordMapper;
import com.icinfo.cloud.provider.punish.ucase.casemain.mapper.CaseProsecutionMapper;
import com.icinfo.cloud.provider.punish.ucase.casemain.model.CaseHandlePersonRecord;
import com.icinfo.cloud.provider.punish.ucase.casemain.model.CaseProsecution;
import com.icinfo.cloud.provider.punish.ucase.casemain.model.CaseProsecutionJudgment;
import com.icinfo.cloud.provider.punish.ucase.casemain.model.CaseProsecutionRegister;
import com.icinfo.cloud.provider.punish.ucase.casemain.service.*;
import com.icinfo.cloud.provider.punish.ucase.casemain.vo.CaseInfoQueryVo;
import com.icinfo.cloud.provider.punish.ucase.casemain.vo.CaseProsecutionJudgmentVo;
import com.icinfo.cloud.provider.punish.ucase.casemain.vo.CaseProsecutionRegisterVo;
import com.icinfo.cloud.provider.punish.ucase.casemain.vo.CaseProsecutionVo;
import com.icinfo.cloud.xzcf.provider.member.role.api.UserRoleFeignApi;
import com.icinfo.cloud.xzcf.provider.member.userinfo.dto.UserDTO;
import com.icinfo.cloud.xzcf.provider.member.userrole.model.MemberUserRole;
import com.icinfo.framework.core.service.support.MyBatisServiceSupport;
import com.icinfo.framework.mybatis.mapper.entity.Example;
import com.icinfo.framework.mybatis.pagehelper.PageHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 描述:  case_prosecution 对应的Service接口实现类.<br>
 *
 * @author framework generator
 * @date 2022年12月01日
 */
@Service
public class CaseProsecutionServiceImpl extends MyBatisServiceSupport implements ICaseProsecutionService {
    /**
     * 日志记录器
     */
    private static final Logger logger = LoggerFactory.getLogger(CaseProsecutionServiceImpl.class);

    @Resource
    private CaseProsecutionMapper caseProsecutionMapper;

    @Resource
    private CaseHandlePersonRecordMapper caseHandlePersonRecordMapper;

    @Autowired
    private ICaseMainInfoService caseMainInfoService;

    @Autowired
    private ICaseProsecutionRegisterService caseProsecutionRegisterService;

    @Autowired
    private ICaseHandlePersonAdjustInfoService caseHandlePersonAdjustInfoService;

    @Autowired
    private ICaseProsecutionJudgmentService caseProsecutionJudgmentService;

    @Autowired
    private UserRoleFeignApi userRoleFeignApi;

    @Autowired
    private ExternalService externalService;

    @Value("${spring.profiles.active}")
    private String profile;

    /**
     * 法制人员 角色id列表
     */
    private List<String> lawRoleIdList = new ArrayList<String>() {{
        add("17EEC349604F4CF8BBF062D850EC4E00");
        add("177AF39B5E3C4B2BA966087A29875442");
    }};

    /**
     * 分页获取案件诉讼列表
     *
     * @param request 请求对象
     * @return 诉讼列表
     * @author lilihao
     * @date 2022/12/5 0:45
     */
    @Override
    public PageResponse<CaseProsecutionVo> getPageList(CaseProsecutionPageQueryRequest request) {
        request.setCaseOrgCode(UserUtil.getUserInfo().getOrgCode());
        PageHelper.startPage(request.getPageNum(), request.getLength());
        List<CaseProsecutionVo> list = caseProsecutionMapper.getPageList(request);
        list.forEach(a -> {
            a.setCaseStatusName(CaseStatusEnum.getValueByCode(a.getCaseStatus()));
            //查询承办人
            String caseId = a.getCaseId();
            //1.循环设置处理人员
            Example example = new Example(CaseHandlePersonRecord.class);
            example.createCriteria().andEqualTo("caseId", caseId).andEqualTo("status", Constant.STRING_1);
            example.orderBy("handlePersonType").asc();
            List<CaseHandlePersonRecord> handlePersonRecords = caseHandlePersonRecordMapper.selectByExample(example);
            String handPersonName = handlePersonRecords.stream().map(p -> p.getHandlePersonName()).collect(Collectors.joining(","));
            a.setHandleName(handPersonName);
            String partyName = caseHandlePersonAdjustInfoService.getPartyName(a.getCaseId());
            a.setPartyName(partyName);
        });
        return new PageResponse<>(list);
    }

    /**
     * 获取案件诉讼详情
     *
     * @param idDto 请求对象
     * @return 诉讼详情列表
     * @author lilihao
     * @date 2022/12/5 16:11
     */
    @Override
    public Dict getDetail(CaseProsecutionIdDto idDto) {
        //1.获取案件诉讼详情
        CaseProsecution caseProsecution = caseProsecutionMapper.selectByPrimaryKey(idDto.getId());
        if (ObjectUtil.isNull(caseProsecution)) {
            throw new BusinessException("案件诉讼不存在");
        }
        Dict dict = Dict.create();
        //2.获取一审登记
        CaseProsecutionRegister prosecutionRegister = CaseProsecutionRegister.builder().caseId(caseProsecution.getCaseId())
                .documentNumber(caseProsecution.getDocumentNumber())
                .trialState(Constant.STRING_1).build();
        CaseProsecutionRegisterVo prosecutionRegister1 = caseProsecutionRegisterService.getInfo(prosecutionRegister);
        if (ObjectUtil.isNotNull(prosecutionRegister1)) {
            dict.put(Constant.STRING_1, prosecutionRegister1);
            //3.获取一审已判决
            CaseProsecutionJudgment caseProsecutionJudgment = CaseProsecutionJudgment.builder().caseId(caseProsecution.getCaseId())
                    .documentNumber(caseProsecution.getDocumentNumber())
                    .trialState(Constant.STRING_2).build();
            CaseProsecutionJudgmentVo caseProsecutionJudgmentVo2 = caseProsecutionJudgmentService.getInf(caseProsecutionJudgment);
            if (ObjectUtil.isNotNull(caseProsecutionJudgmentVo2) && StrUtil.isNotBlank(caseProsecutionJudgmentVo2.getHandleResult())) {

                dict.put(Constant.STRING_2, caseProsecutionJudgmentVo2);
                //4.获取二审登记
                prosecutionRegister.setTrialState(Constant.STRING_3);
                CaseProsecutionRegisterVo prosecutionRegister3 = caseProsecutionRegisterService.getInfo(prosecutionRegister);
                if (ObjectUtil.isNotNull(prosecutionRegister3)) {
                    dict.put(Constant.STRING_3, prosecutionRegister3);
                    //5.获取二审已判决
                    caseProsecutionJudgment.setTrialState(Constant.STRING_4);
                    CaseProsecutionJudgmentVo caseProsecutionJudgmentVo4 = caseProsecutionJudgmentService.getInf(caseProsecutionJudgment);
                    if (ObjectUtil.isNotNull(caseProsecutionJudgmentVo4) && StrUtil.isNotBlank(caseProsecutionJudgmentVo4.getHandleResult())) {
                        dict.put(Constant.STRING_4, caseProsecutionJudgmentVo4);
                    }
                }
            }
        }
        return dict;
    }

    /**
     * 获取诉讼登记信息
     *
     * @param idDto 请求对象
     * @return 诉讼登记信息
     * @author lilihao
     * @date 2022/12/5 16:16
     */
    @Override
    public CaseProsecutionRegisterVo getRegisterInfo(CaseProsecutionIdDto idDto) {
        //1.获取案件诉讼详情
        CaseProsecution caseProsecution = caseProsecutionMapper.selectByPrimaryKey(idDto.getId());
        if (ObjectUtil.isNull(caseProsecution)) {
            throw new BusinessException("案件诉讼不存在");
        }
        //如果为审理状态为（一审已判决）
        String trialState = caseProsecution.getTrialState();
        if (Constant.STRING_2.equals(trialState)) {
            //查询一审登记信息
            trialState = Constant.STRING_1;
        }
        CaseProsecutionRegister prosecutionRegister = CaseProsecutionRegister.builder().caseId(caseProsecution.getCaseId())
                .documentNumber(caseProsecution.getDocumentNumber())
                .trialState(trialState).build();
        CaseProsecutionRegisterVo caseProsecutionRegisterVo = caseProsecutionRegisterService.getInfo(prosecutionRegister);
        if (Constant.STRING_2.equals(caseProsecution.getTrialState()) && ObjectUtil.isNotNull(caseProsecutionRegisterVo)) {
            //如果审理状态为（一审已判决），多余字段置空
            caseProsecutionRegisterVo.setId(null);
            //设置法院审理状态为二审
            caseProsecutionRegisterVo.setTrialState(Constant.STRING_3);
            caseProsecutionRegisterVo.setCourtCaseNumber(null);
            caseProsecutionRegisterVo.setLitigationRegisterTime(null);
            caseProsecutionRegisterVo.setFileList(null);
        }
        return caseProsecutionRegisterVo;
    }

    /**
     * 获取关联案件列表
     *
     * @param queryNameDto 请求对象
     * @return 关联案件列表
     * @author lilihao
     * @date 2022/12/4 21:09
     */
    @Override
    public List<CaseInfoQueryVo> getRelCaseList(CaseInfoQueryNameDto queryNameDto) {
        return caseMainInfoService.getRelCaseList(queryNameDto);
    }

    /**
     * 保存诉讼信息
     *
     * @param saveDto 存储信息
     * @return 状态：1 保存成功
     * @author lilihao
     * @date 2022/12/4 23:02
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int saveRegisterInfo(CaseProsecutionRegisterSaveDto saveDto) {
        //1.判断登记诉讼是否已存在
        Example example = new Example(CaseProsecution.class);
        example.createCriteria()
                .andEqualTo("caseId", saveDto.getCaseId())
                .andEqualTo("isDeleted", "0")
                .andEqualTo("documentNumber", saveDto.getDocumentNumber());
        List<CaseProsecution> list = caseProsecutionMapper.selectByExample(example);
        if (CollectionUtil.isNotEmpty(list) && Integer.parseInt(list.get(0).getTrialState()) >= Integer.parseInt(saveDto.getTrialState())) {
            throw new BusinessException("该案件该文书已登记诉讼，请勿重复操作");
        }

        //2.保存登记诉讼信息
        CaseProsecutionRegister caseProsecutionRegister = BeanUtil.toBean(saveDto, CaseProsecutionRegister.class);
        if (CollectionUtil.isNotEmpty(saveDto.getFileList())) {
            caseProsecutionRegister.setLitigationFile(JSONUtil.toJsonStr(saveDto.getFileList()));
        }
        caseProsecutionRegisterService.saveInfo(caseProsecutionRegister);

        //3.列表为空,保存诉讼信息
        if (CollectionUtil.isEmpty(list)) {
            CaseProsecution prosecution = CaseProsecution.builder()
                    .id(BaseUtil.createUid())
                    .caseId(saveDto.getCaseId())
                    .trialState(saveDto.getTrialState())
                    .litigationRegisterTime(saveDto.getLitigationRegisterTime())
                    .documentNumber(saveDto.getDocumentNumber())
                    .documentApproveTime(saveDto.getDocumentApproveTime())
                    .createTime(new Date())
                    .isDeleted(Constant.STRING_0)
                    .createUserId(String.valueOf(UserUtil.getUserInfo().getUserId()))
                    .build();
            return caseProsecutionMapper.insert(prosecution);
        } else {
            //更新诉讼登记状态
            CaseProsecution prosecution = CaseProsecution.builder()
                    .trialState(saveDto.getTrialState())
                    .updateTime(new Date())
                    .updateUserId(String.valueOf(UserUtil.getUserInfo().getUserId()))
                    .build();
            Example example1 = new Example(CaseProsecution.class);
            example1.createCriteria()
                    .andEqualTo("caseId", saveDto.getCaseId())
                    .andEqualTo("isDeleted", "0")
                    .andEqualTo("documentNumber", saveDto.getDocumentNumber());
            return caseProsecutionMapper.updateByExampleSelective(prosecution, example1);
        }
    }

    /**
     * 更新登记信息
     *
     * @param saveDto 存储信息
     * @return 状态：1 更新成功
     * @author lilihao
     * @date 2022/12/4 23:02
     */
    @Override
    public int updateRegisterInfo(CaseProsecutionRegisterSaveDto saveDto) {
        //1.获取之前案件登记信息
        CaseProsecutionRegister caseProsecutionRegister = caseProsecutionRegisterService.getInfoById(saveDto.getId());

        //2.判断登记诉讼是否已存在
        Example example = new Example(CaseProsecution.class);
        example.createCriteria()
                .andEqualTo("caseId", saveDto.getCaseId())
                .andEqualTo("isDeleted", "0")
                .andEqualTo("documentNumber", saveDto.getDocumentNumber());
        List<CaseProsecution> list = caseProsecutionMapper.selectByExample(example);
        boolean flag = StrUtil.format("{}{}", saveDto.getCaseId(), saveDto.getDocumentNumber()).equals(
                StrUtil.format("{}{}", caseProsecutionRegister.getCaseId(), caseProsecutionRegister.getDocumentNumber()));
        if (!flag && CollectionUtil.isNotEmpty(list) && Integer.parseInt(list.get(0).getTrialState()) >= Integer.parseInt(saveDto.getTrialState())) {
            throw new BusinessException("该案件该文书已登记诉讼，请勿重复操作");
        }

        //2.更新案件诉讼信息
        Example example1 = new Example(CaseProsecution.class);
        example1.createCriteria()
                .andEqualTo("caseId", caseProsecutionRegister.getCaseId())
                .andEqualTo("isDeleted", "0")
                .andEqualTo("documentNumber", caseProsecutionRegister.getDocumentNumber());
        CaseProsecution prosecution = CaseProsecution.builder().caseId(saveDto.getCaseId())
                .trialState(saveDto.getTrialState())
                .litigationRegisterTime(saveDto.getLitigationRegisterTime())
                .documentNumber(saveDto.getDocumentNumber())
                .documentApproveTime(saveDto.getDocumentApproveTime())
                .updateTime(new Date())
                .updateUserId(String.valueOf(UserUtil.getUserInfo().getUserId()))
                .build();
        caseProsecutionMapper.updateByExampleSelective(prosecution, example1);

        //2.更新诉讼登记信息
        CaseProsecutionRegister prosecutionRegister = BeanUtil.toBean(saveDto, CaseProsecutionRegister.class);
        if (CollectionUtil.isNotEmpty(saveDto.getFileList())) {
            prosecutionRegister.setLitigationFile(JSONUtil.toJsonStr(saveDto.getFileList()));
        } else {
            prosecutionRegister.setLitigationFile("");
        }
        caseProsecutionRegisterService.updateInfo(prosecutionRegister);
        return 1;
    }

    /**
     * 删除诉讼信息
     *
     * @param idDto 存储信息
     * @return 状态：1 更新成功
     * @author lilihao
     * @date 2022/12/4 23:02
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int delInfo(CaseProsecutionIdDto idDto) {
        //1.获取诉讼信息
        CaseProsecution caseProsecution = caseProsecutionMapper.selectByPrimaryKey(idDto.getId());
        if (ObjectUtil.isNull(caseProsecution)) {
            throw new BusinessException("案件诉讼信息不存在");
        }

        //2.删除案件诉讼登记信息
        CaseProsecutionRegister caseProsecutionRegister = CaseProsecutionRegister.builder().caseId(caseProsecution.getCaseId())
                .documentNumber(caseProsecution.getDocumentNumber())
                .trialState(caseProsecution.getTrialState()).build();
        caseProsecutionRegisterService.delInfo(caseProsecutionRegister);

        //3.如果法院审理状态为一审中
        CaseProsecution prosecution = CaseProsecution.builder().id(caseProsecution.getId()).build();
        if (Constant.STRING_1.equals(caseProsecution.getTrialState())) {
            //删除案件诉讼信息
            prosecution.setIsDeleted(Constant.STRING_1);
        } else {
            //更新审理状态
            prosecution.setTrialState(Constant.STRING_2);
        }
        return caseProsecutionMapper.updateByPrimaryKeySelective(prosecution);
    }

    /**
     * 获取诉讼判决信息
     *
     * @param idDto 请求id
     * @return 诉讼判决信息
     * @author lilihao
     * @date 2022/12/5 3:55
     */
    @Override
    public CaseProsecutionJudgmentVo getJudgmentInfo(CaseProsecutionIdDto idDto) {
        //1.获取诉讼信息
        CaseProsecution caseProsecution = caseProsecutionMapper.selectByPrimaryKey(idDto.getId());
        if (ObjectUtil.isNull(caseProsecution)) {
            throw new BusinessException("案件诉讼信息不存在");
        }

        //2.判决是否已存在
        String trialState = Constant.STRING_1.equals(caseProsecution.getTrialState()) ? Constant.STRING_2 : Constant.STRING_4;
        CaseProsecutionJudgment caseProsecutionJudgment = CaseProsecutionJudgment.builder().caseId(caseProsecution.getCaseId())
                .documentNumber(caseProsecution.getDocumentNumber())
                .trialState(trialState)
                .build();

        CaseProsecutionJudgmentVo prosecutionJudgmentVo = caseProsecutionJudgmentService.getInf(caseProsecutionJudgment);

        //3.判决已存在，直接返回信息
        if (ObjectUtil.isNotNull(prosecutionJudgmentVo)) {
            return prosecutionJudgmentVo;
        }

        //4.获取法院案号代码
        CaseProsecutionRegister prosecutionRegister = CaseProsecutionRegister.builder().caseId(caseProsecution.getCaseId())
                .documentNumber(caseProsecution.getDocumentNumber())
                .trialState(caseProsecution.getTrialState()).build();
        CaseProsecutionRegisterVo prosecutionRegisterVo = caseProsecutionRegisterService.getInfo(prosecutionRegister);
        if (ObjectUtil.isNull(prosecutionRegisterVo)) {
            throw new BusinessException("案件诉讼登记信息不存在");
        }

        //5.判决不存在，调用irs接口，并且存储到登记表中
        if (profile.equals("prd") || profile.equals("pre")) {
            CaseProsecutionJudgment judgmentInfo = externalService.getJudgmentInfo(prosecutionRegisterVo.getCourtCaseNumber());
            if (ObjectUtil.isNotNull(judgmentInfo)) {
                judgmentInfo.setId(BaseUtil.createUid());
                judgmentInfo.setCaseId(caseProsecution.getCaseId());
                judgmentInfo.setDocumentNumber(caseProsecution.getDocumentNumber());
                judgmentInfo.setTrialState(trialState);
                caseProsecutionJudgmentService.saveInfo(judgmentInfo);
                CaseProsecutionJudgmentVo caseProsecutionJudgmentVo = BeanUtil.toBean(judgmentInfo, CaseProsecutionJudgmentVo.class);
                return caseProsecutionJudgmentVo;
            }
        } else {
            //todo 模拟数据
            CaseProsecutionJudgment prosecutionJudgment1 = CaseProsecutionJudgment.builder().id(BaseUtil.createUid()).caseId(caseProsecution.getCaseId())
                    .documentNumber(caseProsecution.getDocumentNumber())
                    .courtCaseNumber("案件号代码")
                    .partyName("当事人").entName("单位名称")
                    .address("联系地址").phone("联系电话").judgmentTime(new Date())
                    .effectiveDate(new Date()).unicode("统一社会信用代码")
                    .number("序号").trialState(trialState).identityNo("360423199407241316")
                    .judgmentResult("判决结果11").build();
            //获取成功存储登记表，返回数据
            //获取失败，返回未获取成功信息，前端调用接口10秒钟，超时提示获取失败
            caseProsecutionJudgmentService.saveInfo(prosecutionJudgment1);
            CaseProsecutionJudgmentVo caseProsecutionJudgmentVo = BeanUtil.toBean(prosecutionJudgment1, CaseProsecutionJudgmentVo.class);
            return caseProsecutionJudgmentVo;
        }
        return null;
    }

    /**
     * 保存诉讼判决信息
     *
     * @param saveDto 保存信息
     * @return 状态：1：存储成功，
     * @author lilihao
     * @date 2022/12/5 4:01
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public int saveJudgmentInfo(CaseProsecutionJudgmentSaveDto saveDto) {
        //1.获取判决信息
        CaseProsecutionJudgment prosecutionJudgment = caseProsecutionJudgmentService.getInfById(saveDto.getId());
        if (ObjectUtil.isNull(prosecutionJudgment)) {
            throw new BusinessException("案件判决信息不存在");
        }

        //2.更新诉讼判决信息
        CaseProsecutionJudgment caseProsecutionJudgment = CaseProsecutionJudgment.builder()
                .id(saveDto.getId()).caseId(saveDto.getCaseId())
                .documentNumber(prosecutionJudgment.getDocumentNumber())
                .handleResult(saveDto.getHandleResult())
                .remark(saveDto.getRemark())
                .trialState(prosecutionJudgment.getTrialState()).build();
        if (CollectionUtil.isNotEmpty(saveDto.getFileList())) {
            caseProsecutionJudgment.setLitigationFile(JSONUtil.toJsonStr(saveDto.getFileList()));
        }
        caseProsecutionJudgment.setDocumentNumber(prosecutionJudgment.getDocumentNumber());
        caseProsecutionJudgmentService.updateInfo(caseProsecutionJudgment);

        //3.更新案件诉讼法院审理状态
        Example example = new Example(CaseProsecution.class);
        example.createCriteria()
                .andEqualTo("caseId", saveDto.getCaseId())
                .andEqualTo("isDeleted", "0")
                .andEqualTo("documentNumber", prosecutionJudgment.getDocumentNumber());
        CaseProsecution caseProsecution = new CaseProsecution();
        caseProsecution.setTrialState(prosecutionJudgment.getTrialState());
        caseProsecution.setUpdateTime(new Date());
        caseProsecution.setUpdateUserId(String.valueOf(UserUtil.getUserInfo().getUserId()));
        return caseProsecutionMapper.updateByExampleSelective(caseProsecution, example);
    }

    /**
     * 是否拥有法治人员角色
     *
     * @return true:是，false：否
     * @author lilihao
     * @date 2022/12/6 19:49
     */
    @Override
    public boolean isHaveLawRole() {
        UserDTO userInfo = UserUtil.getUserInfo();
        List<MemberUserRole> list = userRoleFeignApi.getMemberUserRoleList(String.valueOf(userInfo.getUserId()), userInfo.getOrgCode(), lawRoleIdList);
        return CollectionUtil.isNotEmpty(list);
    }
}